<template>
  <view>
    <view class="content" @touchstart="hideDrawer">
      <scroll-view
        class="msg-list dialogue-box"
        ref="dialogueBox"
        scroll-y
        :scroll-top="scrollTop"
        @scrolltoupper="loadHistory"
      >
        <view class="dialogue-box-content" ref="dialogueBoxContent">
          <view
            class="row"
            v-for="(row, index) in msgList"
            :key="index"
            :id="'msg' + row.msg.id"
          >
            <!-- 用户消息 -->
            <block v-if="row.type == 'user'">
              <!-- 自己发出的消息 -->
              <view class="my" v-if="row.msg.userinfo.uid == myuid">
                <!-- 左-消息 -->
                <view class="left">
                  <!-- 文字消息 -->
                  <view
                    v-if="row.msg.type == 'text'"
                    class="bubble"
                    @click="copyText(row)"
                  >
                    <view>{{ row.msg.content.text }}</view>
                  </view>
                  <!-- 语言消息 -->
                  <view
                    v-if="row.msg.type == 'voice'"
                    class="bubble voice"
                    @tap="playVoice(row.msg)"
                    :class="playMsgid == row.msg.id ? 'play' : ''"
                  >
                    <view class="length">{{ row.msg.content.length }}</view>
                    <view class="icon my-voice"></view>
                  </view>
                </view>
                <!-- 右-头像 -->
                <view class="right">
                  <image src="@/static/right-header.png"></image>
                </view>
              </view>
              <!-- 别人发出的消息 -->
              <view
                v-if="row.msg.userinfo.uid != myuid"
                style="
                  display: flex;
                  flex-direction: column;
                  /* align-items: flex-end; */
                "
              >
                <view class="other">
                  <!-- 左-头像 -->
                  <view class="left">
                    <image src="@/static/left-header.png"></image>
                  </view>
                  <!-- 右-用户名称-时间-消息 -->
                  <view class="right">
                    <!-- 文字消息 -->
                    <view
                      v-if="row.msg.type == 'text'"
                      class="bubble"
                      @click="copyText(row)"
                    >
                      <view>{{ row.msg.content.text }}</view>
                    </view>
                    <!-- 语音消息 -->
                    <view
                      v-if="row.msg.type == 'voice'"
                      class="bubble voice"
                      @tap="playVoice(row.msg)"
                      :class="playMsgid == row.msg.id ? 'play' : ''"
                    >
                      <view class="icon other-voice"></view>
                      <view class="length">{{ row.msg.content.length }}</view>
                    </view>
                  </view>
                </view>
                <view
                  class="anawer-tips"
                  v-show="
                    index == msgList.length - 1 && appendContent && !ifStopSock
                  "
                  @click="stopSock"
                  >停止回答</view
                >
              </view>
              <view
                class="comment"
                v-if="row.msg.userinfo.uid == 1 && index !== 0"
              >
                <view
                  class="box"
                  :style="{
                    border: row.msg.ifLike === '1' ? '1rpx solid #1E71FF' : '',
                  }"
                  @click="comment('like', row)"
                >
                  <image
                    src="@/static/like.png"
                    v-if="row.msg.ifLike === '0'"
                  ></image
                  ><image
                    src="@/static/like-blue.png"
                    v-if="row.msg.ifLike === '1'"
                  ></image
                  ><span
                    :style="{ color: row.msg.ifLike === '1' ? '#1E71FF' : '' }"
                    >赞</span
                  ></view
                >
                <view
                  class="box"
                  :style="{
                    border:
                      row.msg.ifDisLike === '1' ? '1rpx solid #1E71FF' : '',
                  }"
                  @click="comment('dislike', row)"
                >
                  <image
                    src="@/static/dislike.png"
                    v-if="row.msg.ifDisLike === '0'"
                  ></image
                  ><image
                    src="@/static/dislike-blue.png"
                    v-if="row.msg.ifDisLike === '1'"
                  ></image
                  ><span
                    :style="{
                      color: row.msg.ifDisLike === '1' ? '#1E71FF' : '',
                    }"
                    >踩</span
                  ></view
                >
              </view>
            </block>
            <view v-if="index === 0" class="question-tips other">
              <view class="left">
                <image src="@/static/left-header.png"></image>
              </view>
              <view class="right">
                <view class="question-box">
                  <view class="title">常见</view>
                  <view class="red-img">
                    <image src="@/static/question-bg.png"></image>
                    <view class="title-1">问题</view>
                  </view>
                  <image
                    src="@/static/question-icon.png"
                    class="ques-icon"
                  ></image>
                </view>
                <view>
                  <view
                    v-for="(item, type) in questionList"
                    :key="type"
                    @click="questionBtn(item)"
                    class="question-item"
                    >{{ type + 1 }}、{{ item }}</view
                  >
                </view></view
              >
            </view>
            <view v-if="index === 0 && maskContent" class="wait-tips"
              >当前用户过多，请稍候再试！还有{{ waitSort }}人在等待。</view
            >
          </view>
        </view>
      </scroll-view>
    </view>
    <view
      class="input-box"
      :class="popupLayerClass"
      @touchmove.stop.prevent="discard"
    >
      <!-- <view class="voice">
        <view
          class="icon"
          :class="isVoice ? 'jianpan' : 'yuyin'"
          @tap="switchVoice"
        >
        </view>
      </view> -->
      <view class="textbox">
        <view
          class="voice-mode"
          :class="[isVoice ? '' : 'hidden', recording ? 'recording' : '']"
          @touchstart.prevent="voiceBegin"
          @touchmove.prevent="voiceIng"
          @touchend.prevent="voiceEnd"
          @touchcancel="voiceCancel"
          >{{ voiceTis }}</view
        >
        <view class="text-mode" :class="isVoice ? 'hidden' : ''">
          <view
            class="box"
            :style="{ height: textMsg.length > 80 ? '100px' : '35px', overflowY: textMsg.length > 10 ? 'auto' : 'hidden' }"
          >
            <textarea
              auto-height="true"
              style="height: 35px; overflow: auto"
              v-model="textMsg"
              @focus="textareaFocus"
              :show-confirm-bar="false"
              :cursorSpacing="20"
              maxlength="1000"
            />
          </view>
        </view>
      </view>
      <view
        :class="isVoice ? 'hidden' : ''"
        @tap="sendText"
        style="width: 80rpx,height:100%;"
      >
        <image
          src="@/static/send-btn.png"
          style="
            width: 50rpx;
            height: 50rpx;
            margin-top: 25rpx;
            margin-left: 10rpx;
            padding: 0rpx 30rpx 0rpx 5rpx;
          "
        ></image>
      </view>
    </view>
    <!-- 录音UI效果 -->
    <view class="record" :class="recording ? '' : 'hidden'">
      <view class="ing" :class="willStop ? 'hidden' : ''"
        ><view class="icon luyin2"></view
      ></view>
      <view class="cancel" :class="willStop ? '' : 'hidden'"
        ><view class="icon chehui"></view
      ></view>
      <view class="tis" :class="willStop ? 'change' : ''">{{ recordTis }}</view>
    </view>
  </view>
</template>
<script>
import axios from "axios";
import socket from "plus-websocket";
import {
  requestPermission,
  soundStart,
  soundEnd,
} from "@/utils/soundRecording";
export default {
  data() {
    return {
      //文字消息
      blobUrl: "",
      tempFilePath: "",
      textMsg: "",
      json: "",
      //消息列表
      isHistoryLoading: false,
      scrollAnimation: false,
      scrollTop: 0,
      scrollToView: "",
      msgList: [],
      msgImgList: [],
      myuid: 0,
      rec: null,
      isVoice: false,
      voiceTis: "按住 说话",
      recordTis: "手指上滑 取消发送",
      recording: false,
      willStop: false,
      initPoint: { identifier: 0, Y: 0 },
      recordTimer: null,
      recordLength: 0,

      //播放语音相关参数
      AUDIO: uni.createInnerAudioContext(),
      playMsgid: null,
      VoiceTimer: null,
      // 抽屉参数
      popupLayerClass: "",
      // more参数
      hideMore: true,
      //表情定义
      hideEmoji: true,

      //红包相关参数
      windowsState: "",
      appendContent: "",
      oldSendMsgIndex: 0,
      sSum: null,
      ifStopSock: false,
      eventSource: null,
      questionList: [
        "什么是医保电子凭证?",
        "医保电子凭证如何修改密码?",
        "如何办理异地就医?",
        "什么是亲情账户?",
        "新生儿如何参保?",
      ],
      likeType: 1,
      dislikeType: 1,
      ifLike: 1,
      beginCode: null,
      requestCode: null,
      userId: null,
      maskContent: false,
      waitSort: 0,
      appId: "4751a52272ce494f909ae102babfa59c",
      formData: null,
      isInConversation: false,
    };
  },
  onShow() {},
  onLoad(option) {
    this.getInitCode();
    this.getMsgList();
    // requestPermission();
  },

  methods: {
    //获取initcode
    async getInitCode() {
      uni.request({
        url: "http://121.229.186.197:18858/tzapi/taizhou/session/initCode",
        // url: "http://172.16.15.34:8587/taizhou/session/initCode",
        success: (res) => {
          this.beginCode = res.data.initCode;
          this.scConfig();
          this.scReadey();
        },
      });
    },
    scConfig() {
      if (!this.beginCode) return;
      sc.config({
        debug: false, // 是否开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来
        appId: this.appId, // 在统一 APP 开放平台服务器申请的 appId
        initCode: this.beginCode,
        nativeApis: ["userAuth"],
      });
    },
    scReadey() {
      sc.ready(() => {
        sc.userAuth({ appId: this.appId }, (res) => {
          if (res.code === 0) {
            //    用户同意授权
            this.requestCode = res.data.requestCode;
            this.getUserId();
          } else {
          }
        });
      });
    },
    //获取用户Id
    async getUserId() {
      uni.request({
        url: "http://121.229.186.197:18858/tzapi/taizhou/session/userInfo",
        //  url: "http://172.16.15.34:8587/taizhou/session/userInfo",
        data: { requestCode: this.requestCode },
        method: "GET",
        success: (res) => {
          this.userId = res.data.userId;
          socket.connectSocket({
            url: `ws://121.229.186.197:18858/tzapi/session/taizhou/${res.data.userId}`,
            // url: `ws://172.16.15.34:8587/session/taizhou/${res.data.userId}`,
          });
          socket.onSocketOpen(function (res) {
            console.log("WebSocket连接已确定打开！");
          });
          socket.onSocketMessage((res) => {
            const data = JSON.parse(res.data);
            console.log(res.data, "res");
            this.maskContent = data.await;
            this.waitSort = data.sort;
          });
          socket.onSocketError(function (res) {
            console.log("WebSocket连接打开失败，请检查！");
            socket.connectSocket({
              url: `wss://abc.gszczn.com:18858/tzapi/session/taizhou/${res.data.userId}`,
            });
          });
        },
      });
    },

    // 接受消息(筛选处理)
    screenMsg(msg) {
      //从长连接处转发给这个方法，进行筛选处理
      if (msg.type == "system") {
        // 系统消息
        switch (msg.msg.type) {
          case "text":
            this.addSystemTextMsg(msg);
            break;
        }
      } else if (msg.type == "user") {
        // 用户消息
        switch (msg.msg.type) {
          case "text":
            this.addTextMsg(msg);
            break;
          case "voice":
            this.addVoiceMsg(msg);
            break;
        }
      }
      this.$nextTick(function () {
        // 滚动到底
        this.scrollToView = "msg" + msg.msg.id;
      });
    },
    questionBtn(type) {
      console.log("tingzhi huida ");
      if (this.maskContent) {
        return;
      }
      if (this.isInConversation) {
        return;
      }

      this.textMsg = type;
      this.sendText();
      console.log("12", type);
    },
    stopSock() {
      this.oldSendMsgIndex = 0;
      this.appendContent = "";
      this.ifStopSock = true;
      this.eventSource.onmessage = null;
      this.eventSource.close();
      this.isInConversation = false;
    },
    //触发滑动到顶部(加载历史信息记录)
    loadHistory(e) {
      if (this.isHistoryLoading) {
        return;
      }
      this.isHistoryLoading = true; //参数作为进入请求标识，防止重复请求
      this.scrollAnimation = false; //关闭滑动动画
      let Viewid = this.msgList[0].msg.id; //记住第一个信息ID
      //本地模拟请求历史记录效果
      setTimeout(() => {
        // 消息列表
        let list = [];
        for (let i = 0; i < list.length; i++) {
          list[i].msg.id = Math.floor(Math.random() * 1000 + 1);
          this.msgList.unshift(list[i]);
        }

        //这段代码很重要，不然每次加载历史数据都会跳到顶部
        this.$nextTick(function () {
          this.scrollToView = "msg" + Viewid; //跳转上次的第一行信息位置
          this.$nextTick(function () {
            this.scrollAnimation = true; //恢复滚动动画
          });
        });
        this.isHistoryLoading = false;
      }, 1000);
    },
    // 加载初始页面消息
    getMsgList() {
      // 消息列表
      let list = [
        {
          type: "user",
          msg: {
            id: 2,
            type: "text",
            time: "",
            ifLike: "0",
            ifDisLike: "0",
            userinfo: {
              uid: 1,
              username: "",
              face: "/static/img/im/face/face_2.jpg",
            },
            content: {
              text: "亲爱的用户您好，如果您有跟医保相关的疑问，欢迎向我提问，很高兴为您服务！",
            },
          },
        },
      ];

      this.msgList = list;
      // 滚动到底部
      this.$nextTick(function () {
        //进入页面滚动到底部
        this.$nextTick(function () {
          this.scrollAnimation = true;
        });
      });
    },

    // 隐藏抽屉
    hideDrawer() {
      this.popupLayerClass = "";
      setTimeout(() => {
        this.hideMore = true;
        this.hideEmoji = true;
      }, 150);
    },

    //获取焦点，如果不是选表情ing,则关闭抽屉
    textareaFocus() {
      if (this.popupLayerClass == "showLayer" && this.hideMore == false) {
        this.hideDrawer();
      }
    },
    // 发送文字消息
    async sendText() {
      if (this.maskContent) {
        return;
      }
      if (this.isInConversation) {
        return;
      }
      this.hideDrawer(); //隐藏抽屉
      if (!this.textMsg || this.textMsg.trim() === "") {
        return;
      }
      this.ifStopSock = false;
      // http://172.16.15.34:8587/terminal/lma/chat
      // https://abc.gszczn.com:18858/tzapi/terminal/lma/chat
      this.eventSource = new EventSource(
        "http://121.229.186.197:18858/tzapi/terminal/lma/chat?question=" +
          encodeURIComponent(this.textMsg) +
          "&userId=" +
          encodeURIComponent(this.userId),
        { openWhenHidden: true }
      );
      this.eventSource.onmessage = (event) => {
        const dataContent = event.data;
        var start = event.data.startsWith('{"questionId":');
        if (start) {
          this.isInConversation = true;
          this.messageId = JSON.parse(event.data).questionId;
          console.log(this.messageId);
          return;
        }
        this.appendContent += dataContent;
        if (dataContent === "[end]") {
          this.eventSource.close();
          this.isInConversation = false;
        }
        this.leftMsg(
          this.appendContent,
          "text",
          this.oldSendMsgIndex == 0,
          this.messageId
        );
      };

      this.eventSource.onerror = (error) => {
        console.error("Error receiving SSE:", error);
      };
      this.sendMsg(this.textMsg, "text");
      this.loading = true;
      this.leftMsg("正在思考中...", "text", true, this.messageId);
      this.textMsg = ""; //清空输入框
      console.log(this.msgList);
    },
    copyText(row) {
      const text = row.msg.content.text;
      const textarea = document.createElement("textarea");
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      uni.showToast({
        title: "复制成功",
        icon: "success",
        duration: 1000,
      });
    },
    // 发送消息
    sendMsg(content, type) {
      //消息发出后所做操作
      let lastid = this.msgList[this.msgList.length - 1].msg.id;
      lastid++;
      let msg = {
        type: "user",
        msg: {
          id: lastid,
          time: "",
          type: type,
          userinfo: {
            uid: 0,
            username: "大黑哥",
          },
          content: type == "text" ? { text: content } : { url: content.url },
        },
      };
      // 发送消息
      this.screenMsg(msg);
      // 定时器模拟对方回复,三秒
    },

    leftMsg(content, type, append, messageId) {
      let lastid = this.msgList[this.msgList.length - 1].msg.id;
      if (append) {
        lastid++;
      }
      let msg = {
        type: "user",
        msg: {
          id: lastid,
          time: "",
          ifLike: "0",
          ifDisLike: "0",
          messageId: messageId,
          type: type,
          userinfo: {
            uid: 1,
            username: "",
          },
          content: type == "text" ? { text: content } : { url: content.url },
        },
      };
      // 本地模拟发送消息
      this.screenMsg(msg);
    },

    // 添加文字消息到列表
    addTextMsg(msg) {
      // let msgItem = this.msgList[this.msgList.length - 1].msg;
      if (msg.msg.userinfo.uid == "0") {
        this.msgList.push(msg);
      } else {
        const findIndex = this.msgList.findIndex(
          (it) => it.msg.id === msg.msg.id
        );
        const index = msg.msg.content.text.indexOf("[end]");

        if (findIndex == -1) {
          this.oldSendMsgIndex = findIndex;
          this.msgList.push(msg);
          // uni.vibrateLong();
        } else {
          if (index === -1) {
            this.msgList.splice(findIndex, 1, msg);
          } else {
            this.oldSendMsgIndex = 0;
            this.appendContent = "";
          }
        }
      }
      this.chatScrollTop();
    },

    chatScrollTop() {
      // this.$nextTick(() => {
      const query = uni.createSelectorQuery();
      query.select(".dialogue-box").boundingClientRect();
      query.select(".dialogue-box-content").boundingClientRect();
      query.exec((res) => {
        const scrollViewHeight = res[0].height;
        const scrollContentHeight = res[1].height;
        if (scrollContentHeight > scrollViewHeight) {
          const scrollTop = scrollContentHeight - scrollViewHeight;
          this.scrollTop = scrollTop;
        }
        // });
      });
    },

    debounce(func, delay) {
      let timeoutId;
    },

    // 添加语音消息到列表
    addVoiceMsg(msg) {
      this.msgList.push(msg);
      console.log(this.msgList, "测试发过去的音频");
    },

    // 添加系统文字消息到列表
    addSystemTextMsg(msg) {
      this.msgList.push(msg);
    },

    sendSystemMsg(content, type) {
      let lastid = this.msgList[this.msgList.length - 1].msg.id;
      lastid++;
      let row = {
        type: "system",
        msg: { id: lastid, type: type, content: content },
      };
      this.screenMsg(row);
    },
    // 录音开始
    voiceBegin(e) {
      console.log(e, "点击了录音");
      if (e.touches.length > 1) {
        return;
      }
      this.initPoint.Y = e.touches[0].clientY;
      this.initPoint.identifier = e.touches[0].identifier;

      this.recordBegin();
      soundStart();
    },

    //录音开始UI效果
    recordBegin(e) {
      this.recording = true;
      this.voiceTis = "松开 结束";
      this.recordLength = 0;
      this.recordTimer = setInterval(() => {
        this.recordLength++;
      }, 1000);
    },
    // 录音被打断
    voiceCancel() {
      this.recording = false;
      this.voiceTis = "按住 说话";
      this.recordTis = "手指上滑 取消发送";
      this.willStop = true; //不发送录音
      this.RECORDER.stop(); //录音结束
    },
    // 录音中(判断是否触发上滑取消发送)
    voiceIng(e) {
      if (!this.recording) {
        return;
      }
      let touche = e.touches[0];
      //上滑一个导航栏的高度触发上滑取消发送
      if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
        this.willStop = true;
        this.recordTis = "松开手指 取消发送";
      } else {
        this.willStop = false;
        this.recordTis = "手指上滑 取消发送";
      }
    },
    // 结束录音
    voiceEnd(e) {
      console.log("结束了录音");
      if (!this.recording) {
        return;
      }
      this.recording = false;
      this.voiceTis = "按住 说话";
      this.recordTis = "手指上滑 取消发送";
      soundEnd((info, blob) => {
        console.log(info, blob, "info");
        this.blobUrl = info.filePath;
        uni.uploadFile({
          url: "http://121.229.186.197:18858/tzapi/terminal/lma/identifyVoice",
          //  url: "https://172.16.15.34:8587/terminal/lma/identifyVoice",
          filePath: info.filePath,
          name: "voiceFile",
          success: (uploadRes) => {
            console.log("上传成功", uploadRes);
            // this.leftMsg(uploadRes.data, "text");
            this.textMsg = uploadRes.data;
            this.sendText();
            // 在这里可以处理上传成功后的逻辑
          },
          fail(uploadErr) {
            console.log("上传失败", uploadErr);
            // 在这里可以处理上传失败后的逻辑
          },
        });
      });
    },

    // 切换语音/文字输入
    switchVoice() {
      this.hideDrawer();
      this.isVoice = this.isVoice ? false : true;
      console.log("切换");
    },
    discard() {
      return;
    },
    comment(type, row) {
      if (this.maskContent) {
        return;
      }
      if (row.msg.ifOnceComment && row.msg.ifOnceComment === "1") {
        return;
      }
      row.msg.ifOnceComment = "1";
      if (type === "like") {
        row.msg.ifLike = row.msg.ifLike === "1" ? "0" : "1";
        if (row.msg.ifLike === "1") {
          row.msg.ifDisLike = "0";
        }
      }
      if (type === "dislike") {
        row.msg.ifDisLike = row.msg.ifDisLike === "1" ? "0" : "1";
        if (row.msg.ifDisLike === "1") {
          row.msg.ifLike = "0";
        }
      }
      uni.request({
        url: "http://121.229.186.197:18858/tzapi/terminal/lma/feedback",
        //  url: "http:// 172.16.15.34:8587/terminal/lma/feedback",
        data: { questionId: row.msg.messageId, feedback: row.msg.ifLike },
        success: (res) => {},
      });
    },
  },
  beforeDestroy() {
    socket.closeSocket();
  },
};
</script>
<style lang="scss">
@import "@/static/css/style.scss";
</style>
